﻿using AutoMapper;
using MediatR;
using SlaughterItem.Common.Domains.Detection;
using SlaughterItem.Common.Dtos;
using SlaughterItem.Common.Infrastructures.Interfaces;
using SlaughterItem.Enum;

namespace SlaughterItem.API.Application.Commands.Week02._IPQC.AddIPQCData
{
    /// <summary>
    /// 添加检测标准表数据
    /// </summary>
    public class AddIPQCDataHandler : IRequestHandler<AddIPQCDataCommand, Result>
    {
        public IBaseRepository<IPQCData> IPQCDataRepository;
        public IMapper mapper;

        public AddIPQCDataHandler(IBaseRepository<IPQCData> iPQCDataRepository, IMapper mapper)
        {
            IPQCDataRepository = iPQCDataRepository;
            this.mapper = mapper;
        }

        public async Task<Result> Handle(AddIPQCDataCommand request, CancellationToken cancellationToken)
        {
            var result = new Result() { Code = (int)CommonErrorCode.Added };
            var list = IPQCDataRepository.GetAll().Where(x => x.IPQCId == request.IPQCId).Count();
            if (list > 0)
            {
                return result;
            }
            else
            {
                var IPQCData = mapper.Map<IPQCData>(request);
                var AddNum = IPQCDataRepository.Add(IPQCData);
                if (AddNum > 0)
                {
                    result.Code = IPQCData.IPQCId;
                    return result;
                }
                else
                {
                    return result;
                }
            }
        }
    }
}
